#!/usr/bin/perl
#
# usage:
#   wget --post-data='HOGE node1 node2' -q -O - http://localhost/cgi-bin/limura/Game/destroyJob.cgi'?USER1'
#
# JSON
#   {
#     "Request":"DestroyJob",
#     "GameJobID":"hoge_hoge",
#     "UserName":"USER1",
#     "Nodes":[
#       "node1", "node2", "node3"
#     ]
#   }

require 'config.ph';

$option = join(' ', <>) if($ENV{'REQUEST_METHOD'} eq 'POST');
$option =~ s/\r?\n//g;
if($option =~ m/\{/){
	$jsonObj = from_json($option);
	if(defined($jsonObj) && defined($jsonObj->{"Request"}) && $jsonObj->{"Request"} eq 'DestroyJob'){
		$JobID = $jsonObj->{"GameJobID"};
		$userName = $jsonObj->{"UserName"};
		$nodes = $jsonObj->{"Nodes"};
		$nodes = join(" ", @$nodes);
	}
}
if($userName eq ''){
	&PrintError("UserName not set.");
	exit(0);
}
if($JobID eq ''){
	&PrintError("GameJobID not set.");
	exit(0);
}
unless(open(JOBFILE, "<$HOME_DIR/Game/jobs/$JobID")){
	&PrintError("Invalid GameJobID. GameJobID '$HOME_DIR/Game/jobs/$JobID' file not found.");
	exit(0);
}
@masterJobNames = <JOBFILE>;
close(JOBFILE);
if($#masterJobNames < 0){
	&PrintError("invalid GameJobID.");
	exit(0);
}
$masterURL = &GetMasterURL($userName);
if($masterURL eq ''){
	&PrintError("userName '$userName' not registered.");
	exit(0);
}

foreach $masterJobName (@masterJobNames){
	$masterJobName =~ s/\r?\n$//;
	$masterJobName =~ s/^[^_]+_//;
	`$WGET -q -O - --post-data='$masterJobName $nodes' $masterURL/destroyJob.cgi'?'$userName`;
}
&PrintResult("$JobID on '$nodes' destroyed.");
exit(0);
